<template>
  <div class="app-container">
    <!-- 卡片容器，增加阴影和圆角 -->
    <el-card class="detail-card" shadow="hover" :bordered="false" radius="10px">
      <template #header>
        <div class="card-header">
          <span class="header-title">合同详情</span>
        </div>
      </template>

      <!-- 详情表单，改为两列布局 -->
      <div class="detail-form">
        <div class="form-row">
          <div class="form-label">合同编号</div>
          <div class="form-value">{{ contractDetail.contractNo }}</div>
        </div>
        <div class="form-row">
          <div class="form-label">合同名称</div>
          <div class="form-value">{{ contractDetail.contractName }}</div>
        </div>
        <div class="form-row">
          <div class="form-label">老人姓名</div>
          <div class="form-value">{{ contractDetail.elderlyName }}</div>
        </div>
        <div class="form-row">
          <div class="form-label">老人身份证号</div>
          <div class="form-value">{{ contractDetail.elderlyIdCard }}</div>
        </div>
        <!-- <div class="form-row">
          <div class="form-label">入住单号</div>
          <div class="form-value">{{ checkinmanagementDetail.checkInNo }}</div>
        </div> -->
        <div class="form-row">
          <div class="form-label">合同期限</div>
          <div class="form-value">
            {{ contractDetail.startDate }} —— {{ contractDetail.endDate }}
          </div>
        </div>
        <div class="form-row">
          <div class="form-label">合同状态</div>
          <div class="form-value">
            <el-tag
              :type="getTagType(contractDetail.contractStatus)"
              size="medium"
            >
              {{ contractDetail.contractStatus }}
            </el-tag>
          </div>
        </div>
        <div class="form-row">
          <div class="form-label">签约日期</div>
          <div class="form-value">{{ contractDetail.signTime }}</div>
        </div>
        <div
          class="form-row"
          v-if="contractDetail.partyCName && contractDetail.partyCName.trim()"
        >
          <div class="form-label">丙方姓名</div>
          <div class="form-value">{{ contractDetail.partyCName }}</div>
        </div>

        <!-- 丙方联系方式：有值（非空/非空格）才显示 -->
        <div
          class="form-row"
          v-if="contractDetail.partyCPhone && contractDetail.partyCPhone.trim()"
        >
          <div class="form-label">丙方联系方式</div>
          <div class="form-value">{{ contractDetail.partyCPhone }}</div>
        </div>
        <div class="form-row">
          <!-- <div class="form-label">合同文件</div>
          <div class="form-value">
            <a
              :href="contractDetail.contractFile"
              target="_blank"
              class="view-link"
              >查看</a
            >
          </div> -->
        </div>
      </div>
      <!-- 新增：解除记录模块（仅状态为已失效时显示） -->
      <div
        class="detail-form"
        v-if="contractDetail.contractStatus === '已失效'"
      >
        <div class="form-row-title">解除记录</div>
        <div class="form-row">
          <div class="form-label">解除提交人</div>
          <div class="form-value">
            <!-- 显示匹配到的用户名，无匹配时显示原始ID -->
            {{ getSubmitterName(contractDetail.terminationSubmitter) }}
          </div>
        </div>
        <div class="form-row">
          <div class="form-label">解除日期</div>
          <div class="form-value">{{ contractDetail.terminationTime }}</div>
        </div>
      </div>
      <!-- 底部返回按钮 -->
      <div class="text-right mt-4">
        <el-button type="primary" @click="goBack">返回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup name="ContractDetail">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  listContract,
  getContract,
  delContract,
  addContract,
  updateContract,
} from "@/api/le/contract";
import { listElderly } from "@/api/le/elderly";
import { listUser, getUser } from "@/api/system/user";
import { listCheckinmanagement } from "@/api/le/checkinmanagement";
import { get } from "@vueuse/core";
// 新增：用户列表
const userList = ref([]);
const route = useRoute();
const router = useRouter();
const contractDetail = ref({});
const elderlyList = ref([]);
const checkinmanagementDetail = ref({});
// 新增：获取用户列表
const getUserList = () => {
  return listUser({ pageNum: 1, pageSize: 9999 }).then((response) => {
    userList.value = response.rows;
    console.log("用户列表加载完成：", userList.value);
  });
};
// 新增：根据用户ID获取用户名
const getSubmitterName = (userId) => {
  if (!userId) return "未知";
  const user = userList.value.find(
    (item) => String(item.userId) === String(userId)
  );
  return user ? user.userName : `未知用户(${userId})`;
};
// 获取入住管理详情（确保参数正确传递）
// 获取入住管理详情（修正数组处理逻辑）
const getCheckinmanagementDetail = (checkInManagementId) => {
  // 1. 先判断合同关联的入住ID是否存在
  if (!checkInManagementId) {
    console.log("合同未关联入住管理记录（checkInManagementId为空）");
    checkinmanagementDetail.value = { checkInNo: "暂无关联入住记录" };
    return;
  }

  listCheckinmanagement(checkInManagementId)
    .then((response) => {
      // 2. 接口返回数组（response.rows），先存到变量
      const checkinList = response.rows || [];
      console.log("入住管理接口返回的数组：", checkinList);

      // 3. 关键：从数组中找到与合同checkInManagementId匹配的记录
      // （入住管理表的主键是`id`，合同的`checkInManagementId`关联的就是这个`id`）
      const matchedCheckin = checkinList.find(
        (item) => String(item.id) === String(checkInManagementId)
      );

      // 4. 处理匹配结果
      if (matchedCheckin) {
        checkinmanagementDetail.value = matchedCheckin; // 赋值匹配的单条记录
        console.log("匹配到的入住记录：", matchedCheckin);
        console.log("入住单号checkInNo的值：", matchedCheckin.checkInNo); // 正确打印单号
      } else {
        // 数组有数据，但没找到匹配的记录
        console.log("未找到与合同关联的入住记录");
        checkinmanagementDetail.value = { checkInNo: "暂无关联入住记录" };
      }
    })
    .catch((error) => {
      console.error("获取入住管理详情接口调用失败：", error);
      checkinmanagementDetail.value = { checkInNo: "获取入住记录失败" };
    });
};

// 把 getElderlyList 改为返回 Promise，确保异步顺序
const getElderlyList = () => {
  return listElderly({ pageNum: 1, pageSize: 9999 }).then((response) => {
    elderlyList.value = response.rows;
    console.log("老人列表加载完成：", elderlyList.value); // 日志：查看老人列表数据
  });
};

// 获取合同详情（依赖老人列表）
const getContractDetail = async () => {
  const id = route.params.id;
  //await getElderlyList(); // 等待老人列表加载完成
  await Promise.all([getElderlyList(), getUserList()]);
  getContract(id).then((response) => {
    const data = response.data;
    console.log("合同中的老人外键ID：", data.elderlyId); // 日志：查看合同的elderlyId
    // 关联老人信息（处理数据类型不匹配：转为字符串再比较）
    // 1. 关键日志：确认实体类属性checkInManagementId是否存在且有值
    console.log("合同实体类中的入住管理关联ID：", data.checkInManagementId);
    console.log("合同数据完整结构：", data); // 确认返回的字段里有checkInManagementId
    const elderly = elderlyList.value.find(
      (item) => String(item.id) === String(data.elderlyId)
    );
    if (elderly) {
      data.elderlyName = elderly.name;
      data.elderlyIdCard = elderly.idCard;
      console.log("匹配到的老人信息：", elderly); // 日志：查看匹配结果
    } else {
      data.elderlyName = "暂无关联老人";
      data.elderlyIdCard = "暂无";
      console.log("未匹配到老人：合同elderlyId=" + data.elderlyId);
    }
    // 格式化日期并赋值
    contractDetail.value = {
      ...data,
      startDate: new Date(data.startDate).toISOString().split("T")[0],
      endDate: new Date(data.endDate).toISOString().split("T")[0],
      signTime: new Date(data.signTime).toISOString().split("T")[0],
      // 新增：解除日期格式化（使用自定义函数）
      terminationTime: formatDateTime(data.terminationTime),
      contractStatus: calculateContractStatus(
        data.startDate,
        data.endDate,
        data.terminationTime
      ),
    };
    // 调用获取入住管理详情方法
    getCheckinmanagementDetail(data.checkInManagementId);
  });
};

// 计算合同状态（复用原有逻辑）
function calculateContractStatus(startDate, endDate, terminationTime) {
  const now = new Date();
  const start = new Date(startDate);
  const end = new Date(endDate);
  if (terminationTime) return "已失效";
  if (now < start) return "未生效";
  if (now >= start && now < end) return "生效中";
  if (now >= end) return "已过期";
}

// 返回列表页
const goBack = () => {
  router.push({ path: "/contract/list" });
};
// 合同状态与标签类型映射
const getTagType = (status) => {
  const statusMap = {
    未生效: "info",
    生效中: "success",
    已失效: "danger",
    已过期: "warning",
  };
  return statusMap[status] || "info";
};
// 新增：日期时间格式化函数（转换为 "YYYY-MM-DD HH:mm:ss"）
const formatDateTime = (dateStr) => {
  if (!dateStr) return ""; // 空值返回空字符串，避免显示 "undefined"
  const date = new Date(dateStr);
  // 处理无效日期（如格式错误）
  if (isNaN(date.getTime())) return "无效日期";

  // 补零函数（确保月份/日期/时分秒为两位数）
  const padZero = (num) => num.toString().padStart(2, "0");

  const year = date.getFullYear();
  const month = padZero(date.getMonth() + 1); // 月份从0开始，需+1
  const day = padZero(date.getDate());

  return `${year}-${month}-${day}`;
};
onMounted(() => {
  //   getElderlyList();
  getContractDetail();
});
</script>

<style scoped>
/* 卡片头部样式 */
.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
}
.header-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

/* 详情表单整体布局 */
.detail-form {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.form-row {
  display: flex;
  align-items: center;
}
.form-label {
  width: 120px;
  text-align: right;
  color: #606266;
  font-size: 14px;
  margin-right: 16px;
}
.form-value {
  flex: 1;
  font-size: 14px;
  color: #303133;
}

/* 合同状态标签样式（覆盖Element默认） */
:deep(.el-tag) {
  height: 28px;
  line-height: 28px;
  padding: 0 12px;
  border-radius: 4px;
}
:deep(.el-tag--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

/* 查看链接样式 */
.view-link {
  color: #409eff;
  margin-left: 8px;
  text-decoration: none;
}
.view-link:hover {
  text-decoration: underline;
}

/* 间距调整 */
.mt-4 {
  margin-top: 16px;
}
.form-row-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 20px 0 10px;
}
</style>
